package com.sca4cloud.sca.microservice.controller;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylink.ide.trade.runtime.utils.TradeInvokeUtil;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author lmc
 * @date 2020/04/30
 */
@Slf4j
@RestController("commonController")
//@RequestMapping("/bus")
public class CommonController {

	@Value("#{${gatewayheaders}}")
	public Map<String, String> gatewayheaders;

	@Resource
	private RestTemplate singleTemplate;

	/**
	 * <b>方法描述：</b> 保留分布式部署时网关过来的用户信息（InnerService使用） <br/>
	 * <b>创建者：</b> Yuhq <br/>
	 * <b>创建时间：</b> 2019年3月8日 <br/>
	 */
	private static ThreadLocal<String> currUser = new ThreadLocal<String>();

	private static ThreadLocal<String> currRoles = new ThreadLocal<String>();

	public static String getCurrUser() {
		String strRet = currUser.get();
		currUser.remove();
		return strRet;
	}

	public static String getCurrRoles() {
		String strRet = currRoles.get();
		currRoles.remove();
		return strRet;
	}

	private void delDir(String filepath) {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int nFilesNum = f.listFiles().length;
				for (int j = 0; j < nFilesNum; j++) {
					if (delFile[j].isDirectory()) {
						delDir(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
				f.delete();
			}
		}
	}
	/*
	 * Add end
	 */

	/**
	 * <b>方法描述：</b> 根据主键查询或删除记录 <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param flag       1为查询，2为删除
	 * @param mapperName Mapper名称
	 * @param pk         主键，联合主键时为JSON字符串
	 * @param dbName     数据源名称，undefined时为默认数据源
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/doQuery/{flag}/{mapperName}/{pk}/{dbName}", method = { RequestMethod.GET,
			RequestMethod.DELETE })
	public Object doQuery(@RequestHeader(value = "x-user-header", required = false) Object userCode,
			@RequestHeader(value = "x-role-header", required = false) Object roles,
			@PathVariable(value = "flag") String flag, @PathVariable(value = "mapperName") String mapperName,
			@PathVariable(value = "pk") String pk, @PathVariable(value = "dbName") String dbName) throws Exception {
		Object result = null;

		boolean isComplex = false; // 是否复合主键，复合主键pk是JSON格式 字符串
		try {
			// 查询设置数据权限
			if ("1".equals(flag)) {
				currUser.set(userCode == null ? null : userCode.toString());
				currRoles.set(roles == null ? null : roles.toString());
			}
			pk = Base64.decodeStr(pk);// EncryptUtils.decodeBASE64(pk);
			Map<String, Object> params = new HashMap<>();
			if (pk.startsWith("{")) {
				Map<String, Object> mapType = JSON.parseObject(pk, Map.class);
				params.put("arg0", mapType);
				isComplex = true;
			} else {
				params.put("arg0", pk);
			}
			// 查询
			if ("1".equals(flag)) {
				result = TradeInvokeUtil.doMapper(mapperName, isComplex ? "selectList" : "selectById", dbName, params);

				if (result != null && result instanceof List<?>) {
					List<?> relist = (List<?>) result;
					if (relist.size() > 0)
						result = relist.get(0);
				}
			} else { // 删除
				TradeInvokeUtil.doMapper(mapperName, isComplex ? "delete" : "deleteById", dbName, params);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * <b>方法描述：</b> 数据库新增、修改操作 <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param flag       1为新增，2为更新
	 * @param mapperName Mapper名称
	 * @param dbName     数据源名称，undefined时为默认数据源
	 * @param busData    输入参数
	 * @throws Exception
	 */
	@RequestMapping(value = "/doUpdate/{flag}/{mapperName}/{dbName}", method = { RequestMethod.POST,
			RequestMethod.PUT })
	public Map<String, Object> doUpdate(@PathVariable(value = "flag") String flag,
			@PathVariable(value = "mapperName") String mapperName, @PathVariable(value = "dbName") String dbName,
			@RequestBody Map<String, Object> busdata) throws Exception {
		Map<String, Object> result = new HashMap<>();
		try {
			Map<String, Object> params = new HashMap<>();
			params.put("arg0", busdata);
			// 新增
			if ("1".equals(flag)) {
				TradeInvokeUtil.doMapper(mapperName, "insert", dbName, params);
			} else { // 更新
				TradeInvokeUtil.doMapper(mapperName, "updateById", dbName, params);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * <b>方法描述：</b> 数据库分页查询 <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param mapperName Mapper名称
	 * @param dbName     数据源名称，undefined时为默认数据源
	 * @param busData    输入参数
	 * @throws Exception
	 */
	@RequestMapping(value = "/doPager/{mapperName}/{dbName}", method = RequestMethod.POST)
	public Map<String, Object> doPager(@RequestHeader(value = "x-user-header", required = false) Object userCode,
			@RequestHeader(value = "x-role-header", required = false) Object roles,
			@PathVariable(value = "mapperName") String mapperName, @PathVariable(value = "dbName") String dbName,
			@RequestBody Map<String, Object> busdata) throws Exception {

		Map<String, Object> result = new HashMap<>();
		try {
			currUser.set(userCode == null ? null : userCode.toString());
			currRoles.set(roles == null ? null : roles.toString());
			long current = MapUtil.getLong(busdata, "page");
			long size= MapUtil.getLong(busdata, "limit");

			Map<String, Object> params = new HashMap<>();
			if (StrUtil.isNotEmpty((String) busdata.get("orderByField"))) {
				boolean isAsc = MapUtil.getBool(busdata,"isAsc");
				params.put("isAsc",isAsc);
				params.put("orderCondition", busdata.get("orderByField"));
			}
			busdata.remove("page");
			busdata.remove("limit");
			busdata.remove("orderByField");
			busdata.remove("isAsc");
			if (StrUtil.isNotEmpty((String) busdata.get("_Query_String"))) {
				params.put("_Query_String", busdata.get("_Query_String"));
				busdata.remove("_Query_String");
			}

			if (StrUtil.isNotEmpty((String) busdata.get("sqlWhere"))) {
				StringBuffer sb = new StringBuffer("");
				String[] wheres = ((String) busdata.get("sqlWhere")).split("##");
				for (String where : wheres) {
					sb.append(" and ");
					String[] flds = where.split("---");
					sb.append(flds[0]);
					if ("1".equals(flds[1]))
						sb.append("=");
					else if ("2".equals(flds[1]))
						sb.append("!=");
					else if ("3".equals(flds[1]))
						sb.append(">");
					else if ("4".equals(flds[1]))
						sb.append("<");
					else if ("5".equals(flds[1]))
						sb.append(">=");
					else if ("6".equals(flds[1]))
						sb.append("<=");
					else if ("7".equals(flds[1]))
						sb.append("!<");
					else if ("8".equals(flds[1]))
						sb.append("!>");
					else if ("9".equals(flds[1])) {
						sb.append(" like '");
					} else if ("10".equals(flds[1])) {
						sb.append(" in (");
					} else if ("11".equals(flds[1])) {
						sb.append(" not in (");
					} else if ("12".equals(flds[1])) {
						sb.append(" between ");
					}
					// sb.append(flds[2]);

					if ("9".equals(flds[1])) {
						if (!isValidSqlPara("'" + flds[2] + "'", false)) {
							throw new Exception("输入参数非法:" + ("'" + flds[2] + "'"));
						}
						sb.append(flds[2]);
						sb.append("'");
					} else {
						if (!isValidSqlPara(flds[2], ("10".equals(flds[1]) || "11".equals(flds[1])))) {
							throw new Exception("输入参数非法:" + flds[2]);
						}
						sb.append(flds[2]);
					}
					if ("10".equals(flds[1]) || "11".equals(flds[1])) {
						sb.append(")");
					}
				}
				params.put("sqlWhere", sb.toString().substring(5));
				busdata.remove("sqlWhere");
			}

			long resultcnt = 0;
			List<?> records = new ArrayList<>();

			Page page = new Page(current, size, true);
			params.put("arg0", page);
			params.put("arg1", busdata);
			

			// 查询记录总数
			page = (Page) TradeInvokeUtil.doMapper(mapperName, "selectPage", dbName, params);
			// 查询记录
			currUser.set(userCode == null ? null : userCode.toString());
			currRoles.set(roles == null ? null : roles.toString());
//			records = (List<?>) TradeInvokeUtil.doMapper(mapperName, "selectByBeanAndString", dbName, params);
			result.put("total", page.getTotal());
			result.put("records", page.getRecords());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	static boolean isValidSqlPara(String strVal, boolean inWhere) {
		boolean blnInStr = true;
		strVal = strVal.trim();
		if (strVal.startsWith("'")) {
			for (int z = 1; z < strVal.length(); z++) {
				if (strVal.charAt(z) == '\'') {
					blnInStr = !blnInStr;
				} else if (!blnInStr) {
					if (strVal.charAt(z) != ' ' && strVal.charAt(z) != '\t' && strVal.charAt(z) != ',') {
						return false;
					}
					if (!inWhere && strVal.charAt(z) == ',') {
						return false;
					}
				}
			}
		} else {
			for (int z = 0; z < strVal.length(); z++) {
				if ((!Character.isDigit(strVal.charAt(z))) && strVal.charAt(z) != '.' && strVal.charAt(z) != ',') {
					return false;
				}
				if (!inWhere && strVal.charAt(z) == ',') {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * <b>方法描述：</b> 数据库Mapper调用 <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param mapperName Mapper名称
	 * @param methodName 方法名称
	 * @param dbName     数据源名称，undefined时为默认数据源
	 * @param busData    输入参数
	 * @throws Exception
	 */
	@RequestMapping(value = "/doMapper/{mapperName}/{methodName}/{dbName}", method = RequestMethod.POST)
	public Object doMapper(@RequestHeader(value = "x-user-header", required = false) Object userCode,
			@RequestHeader(value = "x-role-header", required = false) Object roles,
			@PathVariable(value = "mapperName") String mapperName,
			@PathVariable(value = "methodName") String methodName, @PathVariable(value = "dbName") String dbName,
			@RequestBody Map<String, Object> busdata) throws Exception {
		Object result = null;
		try {
			currUser.set(userCode == null ? null : userCode.toString());
			currRoles.set(roles == null ? null : roles.toString());
			result = TradeInvokeUtil.doMapper(mapperName, methodName, dbName, busdata);
		} catch (Exception e) {
			log.error("ROXX0002:" + e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * <b>方法描述：</b> 交易调用方法(只适合报文传输) <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param appName 应用名称
	 * @param busCode 交易码
	 * @param busData 交易数据
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/doBusiness/{appName}/{busCode}", method = RequestMethod.POST)
//	@PostMapping("/doBusiness/{appName}/{busCode}")
	public Map<String, Object> doBusiness(@PathVariable(value = "appName") String appName,
			@PathVariable(value = "busCode") String busCode, @RequestBody Map<String, Object> busdata,
			HttpServletRequest request) throws Exception {

		// 是否包含用户
		if (gatewayheaders != null && !gatewayheaders.isEmpty()) {
			log.info("网关 头配置不为空，特殊处理。。。。。。。");
			Map<String, Object> values = new HashMap<String, Object>();
			for (String key : gatewayheaders.keySet()) {
				String value = request.getHeader(gatewayheaders.get(key));
				if (!StrUtil.isBlank(value)) {
					value = URLDecoder.decode(value, "utf-8");
				}
				log.debug("网关 头配置,>>>>key={},value={}", key, value);
				values.put(key, value);
			}
			busdata.put("gatewayheaders", values);
		}

		Enumeration<String> hs = request.getHeaderNames();
		while (hs.hasMoreElements()) {
			String head = hs.nextElement();
			log.info(">>>>header={},value={}", head, request.getHeader(head));
		}

		Map<String, Object> result = new HashMap<>();
		try {
			List<String> attchData = (List<String>) busdata.get("@@BIN_KEYS@@");
			if (CollectionUtil.isNotEmpty(attchData)) {
				for (String dtkey : attchData) {
					busdata.put(dtkey, Base64.decodeStr(MapUtil.getStr(busdata, dtkey)).getBytes());
				}
			}
			result = TradeInvokeUtil.invokeTrade(appName, busCode, busdata);

		} catch (Exception e) {
			log.error("ROXX0002:" + e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 
	 * <b>方法描述：</b> 交易调用(用于下载文件的交易) <br/>
	 * <b>创建者：</b> lmc <br/>
	 * <b>创建时间：</b> 2019年5月22日 下午4:56:18 <br/>
	 *
	 * @param appName
	 * @param busCode
	 * @param busdata
	 * @return
	 * @throws Exception
	 */
//	@SuppressWarnings("unchecked")
//	@RequestMapping(value = "/doDownloadBusiness/{appName}/{busCode}", method = RequestMethod.POST)
//	public void doDownloadBusiness(@PathVariable(value = "appName") String appName,
//			@PathVariable(value = "busCode") String busCode, @RequestBody Map<String, Object> busdata,
//			HttpServletResponse response, HttpServletRequest request) throws Exception {
//		log.info(">>>>>>>>>>>>>>>doDownloadBusiness>>>>>>>>>>>");
//		// 是否包含用户
//		if (gatewayheaders != null && !gatewayheaders.isEmpty()) {
//			log.info("网关 头配置不为空，特殊处理。。。。。。。");
//			Map<String, Object> values = new HashMap<String, Object>();
//			for (String key : gatewayheaders.keySet()) {
//				String value = request.getHeader(gatewayheaders.get(key));
//				if (!StrUtil.isBlank(value)) {
//					value = URLDecoder.decode(value, "utf-8");
//				}
//				log.debug("网关 头配置,>>>>key={},value={}", key, value);
//				values.put(key, value);
//			}
//			busdata.put("gatewayheaders", values);
//		}
//
//		Map<String, Object> result = new HashMap<>();
//		OutputStream os = null;
//		try {
//			List<String> attchData = (List<String>) busdata.get("@@BIN_KEYS@@");
//			if (CollectionUtil.isNotEmpty(attchData)) {
//				for (String dtkey : attchData) {
//					busdata.put(dtkey, Base64.decodeStr(MapUtil.getStr(busdata, dtkey)).getBytes());
//				}
//			}
//			result = (Map<String, Object>) TradeInvokeUtil.invokeTrade(appName, busCode, busdata);
//			response.addHeader("Access-Control-Expose-Headers", "usercode,userMsg");
//			Object code = result.get("resultCode");
//			if (code != null) {
//				String c = (String) code;
//				if ("999".equals(c)) {
//					response.setHeader("usercode", "999");
//					response.setHeader("userMsg", (String) result.get("resultMsg"));
//					// response.sendError(400, (String) result.get("resultMsg"));
//					log.info(">>>>>>>>doDownloadBusiness>>>>>>>>>>>>>msg={}", result.get("resultMsg"));
//				} else {
//					response.setHeader("usercode", "000");
//					byte[] bytes = (byte[]) result.get("fileBytes");
//					if (bytes != null && bytes.length > 0) {
//						String fileName = (String) result.get("fileName");
//						if (StrUtil.isEmpty(fileName))
//							fileName = busCode + ".csv";
//						log.info(">>>>>>>>>>>>>>>doDownloadBusiness>>>>名称>>>>>>>{}", fileName);
//
//						// 配置文件下载
//						response.setContentType("application/octet-stream");
//						// 下载文件能正常显示中文
//						response.setHeader("Content-Disposition",
//								"attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
//						// 实现文件下载
//						os = response.getOutputStream();
//						os.write(bytes);
//						log.info(">>>>>>>>>>>>>导出交易>>>>length={}", bytes.length);
//					}
//				}
//			}
//		} catch (Exception e) {
//			log.error("ROXX0002:" + e.getMessage(), e);
//			response.setHeader("content-type", "blank");
//			response.setHeader("usercode", "999");
//			throw e;
//		}
//
//	}

	/**
	 * <b>方法描述：</b> 交易调用方法(适合字节数组的传输) <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param appName 应用名称
	 * @param busCode 交易码
	 * @param busData 交易数据
	 */
//	@RequestMapping(value = "/doByteArrayBusiness/{appName}/{busCode}", method = RequestMethod.POST)
//	public Map<String, Object> doByteArrayBusiness(@PathVariable(value = "appName") String appName,
//			@PathVariable(value = "busCode") String busCode, byte[] attchByte, HttpServletRequest request)
//			throws Exception {
//		Map<String, Object> result = new HashMap<>();
//		try {
//			Map<String, Object> busdata = new HashMap<>();
//			Enumeration<String> pNames = request.getParameterNames();
//			while (pNames.hasMoreElements()) {
//				String name = pNames.nextElement();
//				String value = request.getParameter(name);
//				busdata.put(name, value);
//			}
//			result = (Map<String, Object>) TradeInvokeUtil.invokeTrade(appName, busCode, busdata);
//		} catch (Exception e) {
//			log.error("ROXX0002:" + e.getMessage(), e);
//			throw e;
//		}
//		return result;
//	}

	/**
	 * <b>方法描述：</b> 交易调用方法(适合有附件的传输) <br/>
	 * <b>创建者：</b> 于建军 <br/>
	 * <b>创建时间：</b> 2018年1月11日 下午2:35:10 <br/>
	 *
	 * @param appName 应用名称
	 * @param busCode 交易码
	 * @param busData 交易数据
	 */
//	@RequestMapping(value = "/doMultiBusiness/{appName}/{busCode}", method = RequestMethod.POST)
//	public Map<String, Object> doMultiBusiness(@PathVariable(value = "appName") String appName,
//			@PathVariable(value = "busCode") String busCode, MultipartFile filebody, HttpServletRequest request)
//			throws Exception {
//
//		Map<String, Object> result = new HashMap<>();
//		try {
//			Map<String, Object> busdata = new HashMap<>();
//			Enumeration<String> pNames = request.getParameterNames();
//			while (pNames.hasMoreElements()) {
//				String name = pNames.nextElement();
//				String value = request.getParameter(name);
//				busdata.put(name, value);
//			}
//			// 是否包含用户
//			if (gatewayheaders != null && !gatewayheaders.isEmpty()) {
//				log.info("网关 头配置不为空，特殊处理。。。。。。。");
//				Map<String, Object> values = new HashMap<String, Object>();
//				for (String key : gatewayheaders.keySet()) {
//					String value = request.getHeader(gatewayheaders.get(key));
//					if (!StrUtil.isBlank(value)) {
//						value = URLDecoder.decode(value, "utf-8");
//					}
//					log.debug("网关 头配置,>>>>key={},value={}", key, value);
//					values.put(key, value);
//				}
//				busdata.put("gatewayheaders", values);
//			}
//
//			log.info(">>>>>>>>>>>>>doMultiBusiness>>>>>>>>>>>busidata={}", busdata);
//			// 是否包含上传文件
//			if (filebody != null && !filebody.isEmpty()) {
//				String filename = (String) busdata.get("filename");
//				if (StrUtil.isEmpty(filename)) {
//					filename = filebody.getOriginalFilename();
//				}
//				if (StrUtil.isBlank(uploadPath)) {
//					log.error("未配置上传文件地址，上传交易失败，请配置上传目录后重试");
//					result.put("retcode", "999");
//					result.put("retmsg", "未配置文件上传地址，不能上传文件");
//					return result;
//				}
//				log.info(">>>>>>>>>>>>>>>>>>>filename={}", filename);
//				log.info(">>>>>>>>>>>>>>>>>>>filepath={}", uploadPath);
//				// 存储文件
//				File temp = new File(uploadPath + filename);
//				filebody.transferTo(temp);
//				// busdata.remove("filebody");
//				busdata.put("filename", filename);
//				busdata.put("filepath", temp.getAbsolutePath());
//			}
//			result = (Map<String, Object>) TradeInvokeUtil.invokeTrade(appName, busCode, busdata);
//		} catch (Exception e) {
//			log.error("ROXX0002:" + e.getMessage(), e);
//			throw e;
//		}
//		return result;
//	}
//
//	@PostMapping("/yfasvr/fileUpload")
//	public Map<String, String> fileUpload(@RequestParam(value = "filepath", required = false) String filepath,
//			@RequestParam(value = "filename", required = false) String filename,
//			@RequestParam(value = "filebody", required = false) MultipartFile filebody) {
//
//		Map<String, String> retMap = new HashMap<String, String>();
//		try {
//			if (StrUtil.isEmpty(filepath)) {
//				retMap.put("retcode", "9001");
//				retMap.put("retmsg", "上传目录不能为空");
//			} else if (StrUtil.isEmpty(filename)) {
//				retMap.put("retcode", "9002");
//				retMap.put("retmsg", "上传文件名不能为空");
//			} else if (filebody == null) {
//				retMap.put("retcode", "9003");
//				retMap.put("retmsg", "上传文件内容不能为空");
//			} else {
//				String localfile = filepath + File.separator + filename;
//				;
//				File tempFile = new File(localfile);
//				if (!tempFile.getParentFile().exists()) {
//					tempFile.getParentFile().mkdirs();
//				}
//				if (tempFile.exists()) {
//					retMap.put("retcode", "9004");
//					retMap.put("retmsg", "上传文件文件已经存在");
//				} else {
//					filebody.transferTo(tempFile);
//					retMap.put("retcode", "0000");
//					retMap.put("retmsg", "上传文件成功");
//					log.info("上传文件:" + localfile + " 成功");
//				}
//			}
//		} catch (Exception e) {
//			log.error("上传文件失败:", e);
//			retMap.put("retcode", "9999");
//			retMap.put("retmsg", "上传文件失败:" + e.getMessage());
//		}
//		return retMap;
//	}
//
//	@PostMapping("/yfasvr/fileRemove")
//	public Map<String, String> fileRemove(@RequestParam(value = "filepath", required = false) String filepath,
//			@RequestParam(value = "filename", required = false) String filename) {
//		Map<String, String> retMap = new HashMap<String, String>();
//		if (StrUtil.isEmpty(filename)) {
//			if (StrUtil.isEmpty(filepath)) {
//				retMap.put("retcode", "9002");
//				retMap.put("retmsg", "上传文件或文件夹名不能为空");
//			} else {
//				if (filepath.charAt(0) != '\\' && filepath.charAt(0) != '/') {
//					filepath = System.getProperty("user.dir") + File.separator + filepath;
//					// 删除文件夹及下面所有子项
//					delDir(filepath);
//				}
//			}
//		} else {
//			if (StrUtil.isEmpty(filepath)) {
//				filepath = System.getProperty("user.dir");
//			} else if (filepath.charAt(0) != '\\' && filepath.charAt(0) != '/') {
//				filepath = System.getProperty("user.dir") + File.separator + filepath;
//			}
//			String localfile = filepath + File.separator + filename;
//			File tempFile = new File(localfile);
//			if (!tempFile.exists() && tempFile.isDirectory()) {
//				retMap.put("retcode", "9003");
//				retMap.put("retmsg", "文件不存在");
//			} else if (tempFile.delete()) {
//				retMap.put("retcode", "0000");
//				retMap.put("retmsg", "文件删除成功");
//			} else {
//				retMap.put("retcode", "9005");
//				retMap.put("retmsg", "文件删除失败,检查文件权限");
//			}
//		}
//		return retMap;
//	}
//
//	@RequestMapping("/yfasvr/fileDownload")
//	public void fileDownload(@RequestParam Map<String, Object> params, HttpServletResponse response) {
//		if (params == null || !params.containsKey("filename") || !params.containsKey("filepath")) {
//			log.error("下载文件名和路径不能为空");
//			response.setHeader("content-type", "blank");
//			response.setHeader("usercode", "901");
//		} else {
//			String fileName = (String) params.get("filename");
//			String filePath = (String) params.get("filepath");
//			filePath = filePath + File.separator + fileName;
//			File file = new File(filePath);
//			if (file.exists()) {
//				OutputStream out = null;
//				try {
//					// 配置文件下载
//					response.setHeader("content-type", "application/octet-stream");
//					response.setContentType("application/octet-stream");
//					// 下载文件能正常显示中文
//					response.setHeader("Content-Disposition",
//							"attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
//					// 实现文件下载
//					out = response.getOutputStream();
//					out.write(FileUtils.readFileToByteArray(file));
//					log.info("下载文件" + filePath + "成功");
//					response.setHeader("usercode", "000");
//				} catch (Exception e) {
//					log.error("下载文件" + filePath + "失败：", e);
//					response.setHeader("content-type", "blank");
//					response.setHeader("usercode", "999");
//				} finally {
//					if (out != null) {
//						try {
//							out.close();
//						} catch (IOException e) {
//							log.error(e.getMessage(), e);
//						}
//					}
//				}
//			} else {
//				log.error("下载文件" + filePath + "失败：文件不存在");
//				response.setHeader("content-type", "blank");
//				response.setHeader("usercode", "902");
//			}
//		}
//	}

}
